import React, { Component } from 'react';
import App from 'layout/App.js'
import CommonModal from './../../components/CommonModal/index.jsx';
import { FormControl, Button, Table, Pagination, Modal, Radio, Select, Popconfirm } from 'tinper-bee';
import { searchWorkFileList, deleteWorkFileList, endWorkFileList } from './workarchives.config.js';
import { vendorsDanger as danger, vendorsSuccess as success, vendorsFmtDate as fmtDate , vendorsWarning as waring, vendorsSetStorage as setStorage} from 'utils/config.js';
import './index.less';
import zhCN from 'rc-calendar/lib/locale/zh_CN';
import enUS from 'rc-calendar/lib/locale/en_US';
import DatePicker from 'bee-datepicker';
import moment from 'moment';
moment.locale('zh-cn');

import Tooltip from 'bee-tooltip';
import 'bee-tooltip/build/Tooltip.css';
const textOverflowIndex = 10; // 控制项目名称在多少个字符后隐藏

export default class WorkFile extends Component {
	constructor(props) {
		super(props);
		this.state = {
			dataList: [],
			count: 0,
			activePage: 1,
			chooseItemIndex: null,
			searchText: '',
			showModal: false,
			endDate: '',
			endRec: null,
		}
	}
	componentDidMount() {
		this.init();
	}
	init = (data = {}) => {
		let _me = this;
		let keyWord = data.key ? data.key : '';
		let keyStart = data.start ? data.start : 0;
		let param = {
			keyword: keyWord,
			pageStart: keyStart,
			pageSize: 10,
			isAjax: 1,
			ieStamp: new Date().getTime()
		};
		searchWorkFileList(param,
			response => {
				let data = response.data;
				if (data.resultCode !== 'busi_ex') {
					data.result.objects.forEach((item, index) => {
						item['key'] = item.pkProject;
						item['approvalDate'] = fmtDate(item.approvalDate);
						item['endDate'] = item['endDate'] == null ? '' : fmtDate(item.endDate);
					})
					if (keyWord && keyStart == 0) {
						_me.setState({
							dataList: data.result.objects,
							count: Math.ceil(data.result.count / 10),
							activePage: 1,
							chooseItemIndex: null
						});
					} else {
						_me.setState({
							dataList: data.result.objects,
							count: Math.ceil(data.result.count / 10)
						});
					}
				} else {
					danger({ 'text': data.exMsg });
				}
			},
			error => { }
		);
	}
	handlerShowDetailPage = rec => () => {
		sessionStorage.setItem('filePkproject', rec.pkProject);
		window.location.href = "./workfiledetail.html";
	}
	handlerShowEdit = (rec, index) => () => {

		// 每次先清空在赋值
		sessionStorage.setItem('filePkSrc', null);
		if (rec.pkSrc !== null) {
			sessionStorage.setItem('filePkSrc', rec.pkSrc);
		}
		sessionStorage.setItem('filePkproject', rec.pkProject);
		window.location.href = "./workeditfileitem.html";
	}
	getState = (rec) => {
		let projectState = '';
		if (rec.projectStatusName) {
			projectState = rec.projectStatusName
		} else {
			switch (rec.projectState) {
				case -1:
					projectState = '创建';
					break;
				case 0:
					projectState = '施工中';
					break;
				case 1:
					projectState = '竣工';
					break;
				case -2:
					projectState = '暂停';
					break;
				case -3:
					projectState = '停工';
			}
		}
		return projectState
	};

	getColumns = () => {
		let _me = this;
		return [
			{ title: "项目编码", dataIndex: "scode", className: 'text-overflow', key: "scode", width: 100 },
			{
				title: "项目名称", dataIndex: "sname", className: 'text-overflow', key: "sname", width: 100,
				render(text, rec, index) {
					return (
						<Tooltip
							className={[text.length > textOverflowIndex ? "show" : "hidden"]}
							inverse
							placement="top" 
							overlay={text}>
							<a className="table-sname" onClick={_me.handlerShowDetailPage(rec)}>{text}</a>
						</Tooltip>
					)
				}
			},
			{ title: "项目描述", dataIndex: "description", className: 'text-overflow', key: "description", width: 200 },
			{ title: "组织", dataIndex: "orgName", className: 'text-overflow', key: "pkOrg", width: 100 },
			{ title: "项目经理", dataIndex: "managerName", key: "managerName", width: 100 },
			{ title: "立项日期", dataIndex: "approvalDate", key: "approvalDate", width: 100 },
			{
				title: "项目状态", dataIndex: "endDate", key: "endDate", width: 100,
				render(text, rec, index) {
					let projectState = _me.getState(rec);
					return projectState
				}
			},
			{ title: "预计复工日期", dataIndex: "preworkresumeDate", key: "preworkresumeDate", width: 100,
				render(text, rec, index) {
					if(rec.projectState === -2) { // 暂停状态
						return text;
					} else {
						return '';
					}
				}
			},
			{ title: "累计停工天数", dataIndex: "workstopdays", key: "workstopdays", width: 100 },
			{
				title: "进度看板", dataIndex: "projectboard", key: "projectboard", width: 100,
				render(text, rec, index) {
					
					return (
						<div className="table-operation">
							<a href="javascript:;" onClick={ ()=>_me.handleJumpProjectBoard(rec, index)}>查看</a>
						</div>
					)
				}
			},
			{
				title: "操作", dataIndex: "y", key: "y", width: 100,
				render(text, rec, index) {
					return <div className="table-operation">
						<a href="javascript:;" onClick={_me.handlerShowEdit(rec, index)}>编辑</a>
						<b className="table-line">|</b>
						<Popconfirm trigger="click" placement="top"
							rootClose={true}
							onClose={() => { _me.handlerDeleteItem(rec, index) }}
							content={<div className="table-delete clearfix">
								<i className="uf uf-exc-c"></i>
								<span>你确定删除该项目么？</span>
								<em>备注：涉及本项目的所有信息将被删除</em>
							</div>}>
							<a href="javascript:;">删除</a>
						</Popconfirm>
						{/*<b className="table-line">|</b>*/}
						{/*<a href="javascript:;" onClick={()=>{_me.handlerShowEndModal(rec, index)}} className={rec.projectState === 1 ? 'disabled-text': ''}>结束</a>*/}
					</div>
				}
			}
		]
	}

	handleJumpProjectBoard =(rec, index)=>{
		if(!rec.hasPlan){
			waring({text:'该项目未编制计划，不能查看进度看板'})
			return
		}else{
			let param = {
				"pkProject" :rec.pkProject,
			}
			setStorage("pkProject", param);
			setStorage("showBreadFlag", {"showBreadFlag" : true} )
			window.location.href="projectboard.html"
		}
	}

	handlerShowEndModal = (rec, index) => {
		if (rec.projectState === 1) return;
		this.setState({
			showModal: true,
			endRec: rec
		});
	}
	handlerDeleteItem = (rec, index) => {
		if (rec.projectState === 1) {
			danger({ 'text': '此项目已经结束，不可以删除！' });
			return;
		}

		if (rec.pkSrc !== null) {
			danger({ 'text': '此项目来自NC，不可以删除！' });
			return;
		}

		let _me = this;
		let param = {
			'changeFlag': rec.changeFlag,
			'pkProject': rec.pkProject,
			'isAjax': 1,
			'ieStamp': new Date().getTime()
		};
		deleteWorkFileList(param,
			res => {
				let data = res.data;
				if (data.resultCode !== 'busi_ex') {
					_me.setState({
						chooseItemIndex: null,
						activePage: 1
					});
					_me.init({ 'key': '' });
				} else {
					danger({ 'text': data.exMsg });
				}
			},
			error => { }
		)
	}
	handlerSaveSearchText = (e) => {
		let value = e.target.value;
		this.setState({
			searchText: value
		});
	}
	handlerGetSearchData = () => {
		this.init({ key: this.state.searchText });
	}
	handlerCreateItem = () => {
		window.location.href = "./workaddfileitem.html";
	}
	handleSelect = (eventKey) => {
		this.init({ 'start': (eventKey - 1) * 10, 'key': this.state.searchText.trim() });
		this.setState({
			activePage: eventKey,
			chooseItemIndex: null,
			recordDate: null
		});
	}
	onhide = () => {
		this.setState({
			showModal: false
		});
	}
	handlerEndClose = () => {
		this.setState({
			showModal: false
		});
	}
	handlerEndConfirm = () => {
		if (this.state.endDate === '') {
			danger({ text: '没有选择结束时间！' });
			return;
		}
		let param = {
			'endDate': this.state.endDate,
			'changeFlag': this.state.endRec.changeFlag,
			'pkProject': this.state.endRec.pkProject
		};
		endWorkFileList(param,
			res => {
				let data = res.data;
				if (data.resultCode !== 'busi_ex') {
					this.init();
				} else {
					danger({ text: data.exMsg })
				}

				this.setState({
					showModal: false
				});
			},
			error => { }
		)
	}
	getComponents = () => {
		return <div className="end--list">
			<div className="end-weight clearfix">
				<span className="name">结束日期：</span>
				<DatePicker
					format={"YYYY-MM-DD"}
					onSelect={this.onEndSelect}
					onChange={this.onChange}
					locale={zhCN}
					placeholder={'选择日期时间'}
					disabledDate={this.disableDate}
				/>
			</div>
		</div>
	}
	onEndSelect = (date) => {
		if (date !== null) {
			this.setState({
				endDate: new Date(date._d).getTime()
			});
		}
	}
	disableDate = (current) => {
		return current && current.valueOf() < new Date(this.state.endRec.approvalDate).getTime();
	}
	onChange = (date) => { }
	render() {
		return (
			<App>
				<CommonModal show={this.state.showModal}
					cancel={this.handlerEndClose}
					confirm={this.handlerEndConfirm}
					hide={this.onhide}
					content={this.getComponents()}
					backdrop={true}
					size={'lg'}
				>
				</CommonModal>
				<div className="file-header clearfix">
					<h4 className="title">项目档案</h4>
					<div className="search-group clearfix">
						<FormControl size="lg" placeholder={`输入项目名称、编码`} onChange={this.handlerSaveSearchText} value={this.state.searchText} />
						<a href="javascript:;" className="search-btn" onClick={this.handlerGetSearchData}></a>
					</div>
					<Button colors="primary" className="create-btn" onClick={this.handlerCreateItem}>创建</Button>
				</div>
				<div className="file-content clearfix">
					<Table
						columns={this.getColumns()}
						data={this.state.dataList}
						emptyText={() => '暂无数据'}
					/>
					<Pagination
						first
						last
						prev
						next
						boundaryLinks
						items={this.state.count}
						maxButtons={5}
						activePage={this.state.activePage}
						onSelect={this.handleSelect}
						className="pagination-position" />

				</div>
			</App>
		)
	}
}